<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" :inline="true">
        <el-form-item label="合作商搜索:">
          <el-input
            v-model="search.name"
            clearable
            placeholder="请输入"
            size="medium"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="medium"
            class="my-primary1"
            icon="el-icon-search"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-row type="flex" class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="showAdd('add')"
        >新建</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="name" label="型号名称" />
        <el-table-column prop="model" label="型号编码" />
        <el-table-column label="设备图片">
          <template v-slot="{ row }">
            <img :src="row.image" class="vm-type-image">
          </template>
        </el-table-column>
        <el-table-column prop="vmRow" label="货道行" />
        <el-table-column prop="vmCol" label="货道列" />
        <el-table-column prop="channelMaxCapacity" label="设备容量" />
        <el-table-column label="操作" width="150">
          <template v-slot="{ row }">
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="recreate(row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              class="el-button--danger-text"
              @click.native="delVmType(row.typeId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          @current-change="vmTypeSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增设备类型"
      :visible.sync="addDialog"
      width="630px"
      top="15vh"
      @close="addClose"
    >
      <el-form
        ref="add"
        :model="addForm"
        :rules="addRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="型号名称：" prop="name">
          <el-input
            v-model="addForm.name"
            autocomplete="off"
            placeholder="请输入"
            style="width: 396px"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="型号编码：" prop="model">
          <el-input
            v-model="addForm.model"
            autocomplete="off"
            placeholder="请输入（限制数字、字母、中划线、下划线）"
            style="width: 396px"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="货道行数：" prop="vmRow">
          <el-input-number
            v-model="addForm.vmRow"
            style="width: 396px"
            placeholder="请输入"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="货道列数：" prop="vmCol">
          <el-input-number
            v-model="addForm.vmCol"
            style="width: 396px"
            placeholder="请输入"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="货道容量：" prop="channelMaxCapacity">
          <el-input-number
            v-model="addForm.channelMaxCapacity"
            style="width: 396px"
            placeholder="请输入"
            controls-position="right"
            :min="1"
            :max="10"
          />
        </el-form-item>
        <el-form-item label="设备图片：" prop="image">
          <div class="common-upload">
            <el-upload
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.png"
              :http-request="uploadImage"
            >
              <template #trigger>
                <img v-if="addForm.image" :src="addForm.image" class="image">
                <div v-else class="common-upload-icon">
                  <svg
                    version="1.1"
                    viewBox="0 0 1024 1024"
                    class="svg-icon svg-fill"
                    style="width: 16px; height: 16px"
                  >
                    <defs />
                    <path
                      pid="0"
                      d="M915.163 448H704v64h211.163c25.6 0 44.837 19.237 44.837 44.763v358.4c0 25.6-19.163 44.837-44.837 44.837H108.91a43.74 43.74 0 0 1-44.837-44.837v-358.4c0-25.6 19.164-44.763 44.837-44.763h211.163v-64h-211.31C51.2 448 0 499.2 0 556.763v358.4C0 972.8 51.2 1024 108.837 1024h806.326C972.8 1024 1024 972.8 1024 915.163v-358.4C1024 499.2 972.8 448 915.163 448zM806.4 281.6L716.8 192 543.963 19.237c-25.6-25.6-44.763-25.6-70.363 0l-128 128C307.2 192 262.437 236.763 217.6 281.6c-12.8 6.363-32.037 31.963-12.8 51.2 6.437 6.437 12.8 12.8 19.237 12.8 12.726 0 25.6-6.363 31.963-19.163C326.437 256 396.8 192 460.8 128l12.8-12.8 6.437-6.363V832h64V108.837l6.363 6.363 19.163 19.163 192 192.074C768 332.8 780.8 345.6 793.6 345.6c6.437 0 12.8-6.363 25.6-12.8 19.237-19.237 0-38.4-12.8-51.2z"
                      _fill="#BAC0CD"
                    />
                  </svg>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名：jpg、png，文件不得大于100kb
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button class="my-secondary" @click="addClose">取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="addSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchVmType,
  addVmType,
  updateVmType,
  delVmType,
  imgUpload
} from '@/api/vm'
export default {
  data() {
    return {
      search: {
        name: '',
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      addDialog: false,
      addForm: {
        name: '',
        model: '',
        vmRow: '',
        vmCol: '',
        channelMaxCapacity: '',
        image: null
      },
      addRules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        model: [
          { required: true, message: '请输入', trigger: 'change' },
          {
            pattern: /^[a-zA-Z0-9_-]+$/g,
            message: '请输入合法的型号编码',
            trigger: 'change'
          }
        ],
        vmRow: [{ required: true, message: '请输入', trigger: 'change' }],
        vmCol: [{ required: true, message: '请输入', trigger: 'change' }],
        channelMaxCapacity: [
          { required: true, message: '请输入', trigger: 'change' }
        ],
        image: [{ required: true, message: '请上传', trigger: 'change' }]
      },
      type: ''
    }
  },
  async created() {
    await this.vmTypeSearch()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.vmTypeSearch()
    },
    async vmTypeSearch() {
      const { currentPageRecords, totalCount, totalPage } = await searchVmType({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = totalPage
      this.tableData = currentPageRecords
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showAdd(type) {
      this.addDialog = true
      this.type = type
    },
    addClose() {
      this.addDialog = false
      this.$refs.add.resetFields()
      this.addForm = {
        name: '',
        model: '',
        vmRow: '',
        vmCol: '',
        channelMaxCapacity: '',
        image: null
      }
    },
    async addSubmit() {
      this.$refs.add.validate(async(isOK) => {
        if (isOK) {
          if (this.type === 'add') {
            await addVmType({ ...this.addForm })
          } else {
            await updateVmType({ ...this.addForm })
          }
          this.addClose()
          this.vmTypeSearch()
        }
      })
    },
    beforeAvatarUpload(file) {
      const isImg = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt100K = file.size / 1024 < 100

      if (!isImg) {
        this.$message.error('上传设备图片只能是 JPG、PNG 格式!')
      }
      if (!isLt100K) {
        this.$message.error('上传设备图片大小不能超过 100KB!')
      }
      return isImg && isLt100K
    },
    async uploadImage(params) {
      const data = new FormData()
      data.append('fileName', params.file)
      this.addForm.image = await imgUpload(data)
    },
    async recreate(row) {
      this.addForm = { ...row }
      this.showAdd('edit')
    },
    async delVmType(id) {
      this.$confirm('您确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delVmType(id)
        if (this.tableData.length === 1) this.search.pageIndex--
        this.vmTypeSearch()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
</style>
